import tkinter as tk
from tkinter import filedialog#用于打开文件  核心：filepath = filedialog.askopenfilename() #获得选择好的文件,单个文件

import argparse
import time
from pathlib import Path

import cv2
import torch
import torch.backends.cudnn as cudnn
from numpy import random, ascontiguousarray


from models.experimental import attempt_load
from utils.datasets import LoadStreams, LoadImages, letterbox
from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
    scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
from utils.plots import plot_one_box
from utils.torch_utils import select_device, load_classifier, time_synchronized

class DETECT_API:
    def __init__(self,opt):
        weights,imgsz = opt.weights,opt.img_size
        self.device = select_device(opt.device)
        # device = device_ if torch.cuda.is_available() else 'cpu'  # 设置代码执行的设备 cuda device, i.e. 0 or 0,1,2,3 or cpu
        # self.device = device
        self.half = self.device.type != 'cpu'  # half precision only supported on CUDA

        # self.imgsz = (imgsz, imgsz)  # 输入图片的大小 默认640(pixels)
        self.conf_thres = opt.conf_thres  # object置信度阈值 默认0.25  用在nms中
        self.iou_thres = opt.iou_thres  # 做nms的iou阈值 默认0.45   用在nms中
        # self.max_det = max_det  # 每张图片最多的目标数量  用在nms中
        self.classes = opt.classes  # 在nms中是否是只保留某些特定的类 默认是None 就是所有类只要满足条件都可以保留 --class 0, or --class 0 2 3
        self.agnostic_nms = opt.agnostic_nms  # 进行nms是否也除去不同类别之间的框 默认False
        self.augment = opt.augment  # 预测是否也要采用数据增强 TTA 默认False
        # self.visualize = False  # 特征图可视化 默认FALSE
        # self.half = False  # 是否使用半精度 Float16 推理 可以缩短推理时间 但是默认是False
        # self.dnn = False  # 使用OpenCV DNN进行ONNX推理


        # Load model
        self.model = attempt_load(weights, map_location=self.device)  # load FP32 model
        if self.half:
            self.model.half()  # to FP16

        if self.device.type != 'cpu':
            self.model(torch.zeros(1, 3, imgsz, imgsz).to(self.device).type_as(next(self.model.parameters())))  # run once

        self.stride = int(self.model.stride.max())  # model stride
        self.imgsz = check_img_size(imgsz, s=self.stride)  # check img_size
        # Get names and colors
        self.names = self.model.module.names if hasattr(self.model, 'module') else self.model.names
        colors = [[random.randint(0, 255) for _ in range(3)] for _ in self.names]

    def detect(self,img_path):
        '''
        检测图像，输入图片路径，不能输入视频路径
        Args:
            img_path: 图片路径

        Returns:字典{'class': cls, 'conf': conf, 'position': xywh}

        '''
        # Set Dataloader
        dataset = LoadImages(img_path, img_size=self.imgsz, stride=self.stride)

        # 用于存放结果
        detections = []
        s = ''
        for path, img, im0s, vid_cap in dataset:
            print(path)
            img = torch.from_numpy(img).to(self.device)
            img = img.half() if self.half else img.float()  # uint8 to fp16/32
            img /= 255.0  # 0 - 255 to 0.0 - 1.0
            if img.ndimension() == 3:
                img = img.unsqueeze(0)

            # Inference
            t1 = time_synchronized()
            pred = self.model(img, augment=self.augment)[0]

            # Apply NMS
            pred = non_max_suppression(pred, self.conf_thres, self.iou_thres, classes=self.classes, agnostic=self.agnostic_nms)
            t2 = time_synchronized()


            # Process detections
            for i, det in enumerate(pred):  # detections per image
                s = '%gx%g ' % img.shape[2:]  # print string
                im0 = im0s
                if len(det):
                    # Rescale boxes from img_size to im0 size
                    det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()

                    # Write results
                    for *xyxy, conf, cls in reversed(det):
                        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4))).view(-1).tolist()
                        xywh = [round(x) for x in xywh]
                        xywh = [xywh[0] - xywh[2] // 2, xywh[1] - xywh[3] // 2, xywh[2],
                                xywh[3]]  # 检测到目标位置，格式：（left，top，w，h）

                        cls = self.names[int(cls)]
                        conf = float(conf)
                        detections.append({'class': cls, 'conf': conf, 'position': xywh})
                        # 输出结果
        for i in detections:
            print(i)
        # Print time (inference + NMS)
        print(f'{s}Done. ({t2 - t1:.3f}s)')
        return detections

    def detect2(self,img):
        '''
        检测图像，输入图片数组
        Args:
            img: 图片数组

        Returns:字典{'class': cls, 'conf': conf, 'position': xywh}

        '''
        # Set Dataloader
        # dataset = LoadImages(img_path, img_size=self.imgsz, stride=self.stride)

        # 用于存放结果
        detections = []
        s = ''
        if True:
            # print(path)
            im0 = img*1
            # Padded resize
            img = letterbox(im0, self.imgsz, stride=self.stride)[0]
            # Convert
            img = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x416
            img = ascontiguousarray(img) # np.ascontiguousarray(img)

            img = torch.from_numpy(img).to(self.device)
            img = img.half() if self.half else img.float()  # uint8 to fp16/32
            img /= 255.0  # 0 - 255 to 0.0 - 1.0
            if img.ndimension() == 3:
                img = img.unsqueeze(0)

            # Inference
            t1 = time_synchronized()
            pred = self.model(img, augment=self.augment)[0]

            # Apply NMS
            pred = non_max_suppression(pred, self.conf_thres, self.iou_thres, classes=self.classes, agnostic=self.agnostic_nms)
            t2 = time_synchronized()


            # Process detections
            for i, det in enumerate(pred):  # detections per image
                s = '%gx%g ' % img.shape[2:]  # print string
                if len(det):
                    # Rescale boxes from img_size to im0 size
                    det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()

                    # Write results
                    for *xyxy, conf, cls in reversed(det):
                        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4))).view(-1).tolist()
                        xywh = [round(x) for x in xywh]
                        xywh = [xywh[0] - xywh[2] // 2, xywh[1] - xywh[3] // 2, xywh[2],
                                xywh[3]]  # 检测到目标位置，格式：（left，top，w，h）

                        cls = self.names[int(cls)]
                        conf = float(conf)
                        detections.append({'class': cls, 'conf': conf, 'position': xywh})
                        # 输出结果
        for i in detections:
            print(i)
        # Print time (inference + NMS)
        print(f'{s}Done. ({t2 - t1:.3f}s)')
        return detections

def select_img():
    global detect_state
    pass
    filepath = filedialog.askopenfilename(title='选择图片',filetypes=[('图片', '*.jpg *.png'), ('All files', '*')])
    label['text'] = filepath
    detect_state = 1
def select_video():
    global detect_state
    pass
    filepath = filedialog.askopenfilename(title='选择视频', filetypes=[('视频', '*.mp4'), ('All files', '*')])
    label['text'] = filepath
    detect_state = 2

def mt_detect():
    global detect_state
    pass
    path = label['text']
    print(path)
    if not detect_state:
        print('请选择图片或视频')
    else:
        # opt.source = path
        if detect_state == 1:
            show_img(path)
        elif detect_state == 2:
            show_video(path)

    detect_state = 0

def show_img(img_path):
    # # 传入图片路径
    # detections = Detect.detect(img_path)

    # print(detections)
    img = cv2.imread(img_path)

    t1 = time.time()
    detections = Detect.detect2(img)
    t2 = time.time()
    for i in detections:
        # print(i)
        x, y, w, h = i['position']
        img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 3)
        img = cv2.putText(img, "{} {}".format(i['class'], round(i['conf'], 4)), (x, y - 5),
                          cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1,
                          cv2.LINE_AA)
    img = cv2.putText(img, "{}s".format( round((t2 - t1), 3)),
                      (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 1, cv2.LINE_AA)

    cv2.imshow('yolov5-Lite img', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

def show_video(video_path):
    cap = cv2.VideoCapture(video_path)
    while cap.isOpened():
        ret, img = cap.read()
        if ret:
            pass
            t1 = time.time()
            detections = Detect.detect2(img)
            t2 = time.time()
            for i in detections:
                # print(i)
                x, y, w, h = i['position']
                img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 3)
                img = cv2.putText(img, "{} {}".format(i['class'], round(i['conf'], 4)), (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1, cv2.LINE_AA)
            img = cv2.putText(img, "{}FPS - {}s".format(round(1/(t2-t1),2), round((t2-t1),3)), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 1,cv2.LINE_AA)

            cv2.imshow('yolov5-Lite img', img)
            # cv2.waitKey(1000)
            if cv2.waitKey(10) == ord('q'):
                break
        else:
            break
    cap.release()
    cv2.destroyAllWindows()



if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', nargs='+', type=str, default='runs/train/exp9/weights/best.pt',
                        help='model.pt path(s)')
    #parser.add_argument('--source', type=str,default='',help='source')  # file/folder, 0 for webcam
    parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
    parser.add_argument('--conf-thres', type=float, default=0.45, help='object confidence threshold')
    parser.add_argument('--iou-thres', type=float, default=0.5, help='IOU threshold for NMS')
    parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
    parser.add_argument('--view-img', action='store_true', help='display results')
    parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
    parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
    parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
    parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
    parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
    parser.add_argument('--augment', action='store_true', help='augmented inference')
    parser.add_argument('--update', action='store_true', help='update all models')
    parser.add_argument('--project', default='runs/detect', help='save results to project/name')
    parser.add_argument('--name', default='exp', help='save results to project/name')
    parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
    opt = parser.parse_args()
    print(opt)
    check_requirements(exclude=('pycocotools', 'thop'))

    # 初始化模型
    Detect = DETECT_API(opt)
    print('初始化完成/n')

    # 界面设计
    detect_state = False
    top = tk.Tk()
    top.title('YOLOV5-Lite Detect')
    top['bg'] = 'white'
    width = 300
    height = 150
    win_width = top.winfo_screenwidth()
    win_height = top.winfo_screenheight()
    center_place = str(int(win_width/2 - width/2))+'+'+str(int(win_height/2 - height/2))
    top.geometry(str(width)+'x'+str(height)+'+'+center_place)

    label = tk.Label(top,text='path')
    label.pack(fill='both')
    btn_img = tk.Button(top,text='选择图片',command=select_img)
    btn_img.pack(fill='both')
    btn_video = tk.Button(top,text='选择视频',command=select_video)
    btn_video.pack(fill='both')

    btn_detect = tk.Button(top,text='DETECT',command=mt_detect)
    btn_detect.pack(fill='both')

    top.mainloop()
